package com.cool.controller;

import com.cool.dao.UserMapper;
import com.cool.dao.WalletMapper;
import com.cool.entity.Wallet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
public class WalletController {
        @Autowired
        private WalletMapper walletMapper;

        @Autowired
        private UserMapper userMapper;

        @RequestMapping(value = "/api/wallet/{userid}",method = RequestMethod.GET,produces = "application/json;charset=utf-8")
        public ResponseEntity<Wallet> getWallet(@PathVariable int userid){
            Wallet wallet=walletMapper.selectByPrimaryKey(userid);
            if(wallet==null){
                return new ResponseEntity<Wallet>(HttpStatus.NO_CONTENT);
            }
            return new ResponseEntity<Wallet>(wallet,HttpStatus.OK);
        }

        @RequestMapping(value = "/api/wallet/{userid}",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
        public ResponseEntity<Wallet> add(@PathVariable int userid){
            if(userMapper.selectByPrimaryKey(userid)==null||walletMapper.selectByPrimaryKey(userid)!=null){
                return new ResponseEntity<Wallet>(HttpStatus.NO_CONTENT);
            }
            Wallet wallet=new Wallet();
            wallet.setUserid(userid);
            wallet.setSurplus("0");
            walletMapper.insert(wallet);
            return new ResponseEntity<Wallet>(wallet,HttpStatus.OK);
        }

        @RequestMapping(value = "/api/wallet",method = RequestMethod.PUT,consumes = "application/json;charset=utf-8",produces = "application/json;charset=utf-8")
        public ResponseEntity<Wallet> update(@RequestBody Wallet wallet){
            if(walletMapper.selectByPrimaryKey(wallet.getUserid())==null){
                return new ResponseEntity<Wallet>(HttpStatus.NO_CONTENT);
            }
            walletMapper.updateByPrimaryKey(wallet);
            Wallet result=walletMapper.selectByPrimaryKey(wallet.getUserid());
            return new ResponseEntity<Wallet>(result,HttpStatus.OK);
        }
}
